package com.example.warehouse.service;

import com.example.warehouse.entity.User;
import com.example.warehouse.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public void createUser(User user) {
        // 首先检查用户名和邮箱是否已经存在
        if (checkUsernameExist(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        if (checkEmailExist(user.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }
        // 插入用户数据
        userMapper.insertUser(user);
    }

    @Override
    public void updateUser(User user) {
        // 这里可以添加一些权限控制，确保只有自己可以修改自己的信息
        userMapper.updateUser(user);
    }

    @Override
    public void deleteUser(Long id) {
        // 删除用户
        userMapper.deleteUser(id);
    }

    @Override
    public boolean checkUsernameExist(String username) {
        return userMapper.findByUsername(username) != null;
    }

    @Override
    public boolean checkEmailExist(String email) {
        return userMapper.findByEmail(email) != null;
    }
}